import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import '../model/training_record.dart';
import '../repository/training_record_repository.dart';

// part 'training_history_event.dart';
import 'training_history_event.dart';
// part 'training_history_state.dart';
import 'training_history_state.dart';

class TrainingHistoryBloc extends Bloc<TrainingHistoryEvent, TrainingHistoryState> {
  final TrainingRecordRepository repository;

  TrainingHistoryBloc({required this.repository}) : super(TrainingHistoryInitial()) {
    on<TrainingHistoryLoaded>(_onLoaded);
    on<TrainingRecordAdded>(_onRecordAdded);
    on<TrainingRecordsCleared>(_onRecordsCleared);
  }

  FutureOr<void> _onLoaded(
    TrainingHistoryLoaded event,
    Emitter<TrainingHistoryState> emit,
  ) async {
    print('TrainingHistoryLoaded event received');
    emit(TrainingHistoryLoading());
    try {
      final records = repository.getAllRecords();
      print('Loaded ${records.length} records from repository');
      emit(TrainingHistoryLoadedSuccess(records));
    } catch (e) {
      print('Error loading records: $e');
      emit(TrainingHistoryError(e.toString()));
    }
  }

  FutureOr<void> _onRecordAdded(
    TrainingRecordAdded event,
    Emitter<TrainingHistoryState> emit,
  ) async {
    print('TrainingRecordAdded event received for record: ${event.record.type}');
    try {
      await repository.addRecord(event.record);
      print('Record added to repository successfully');
      final records = repository.getAllRecords();
      print('Emitting TrainingHistoryLoadedSuccess with ${records.length} records');
      emit(TrainingHistoryLoadedSuccess(records));
    } catch (e) {
      print('Error adding record: $e');
      emit(TrainingHistoryError(e.toString()));
    }
  }

  FutureOr<void> _onRecordsCleared(
    TrainingRecordsCleared event,
    Emitter<TrainingHistoryState> emit,
  ) async {
    emit(TrainingHistoryLoading());
    try {
      await repository.clearRecords();
      emit(TrainingHistoryLoadedSuccess([]));
    } catch (e) {
      emit(TrainingHistoryError(e.toString()));
    }
  }
}